package br.edu.univas.locadoragraph.dao;

import java.util.ArrayList;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.Index;

import br.edu.univas.locadoragraph.database.Keys;
import br.edu.univas.locadoragraph.database.RelTypes;
import br.edu.univas.locadoragraph.to.MovieTO;

public class RelationshipGraph {
	
	public void createRelationshipMovieActor(GraphDatabaseService graph, Node movie, MovieTO movieTo){
		ArrayList<String> actors = movieTo.getActors();
		System.out.println("Create index for actor...");
		Index<Node> index = graph.index().forNodes(Keys.INDEXACTOR);
		Relationship relationship;
		for (String actor : actors) {
			Node node = index.get(Keys.ACTORKEY, actor.toLowerCase()).getSingle();
			System.out.println("Node: " + node);
			relationship = node.createRelationshipTo(movie, RelTypes.SERVED);
		}
	}
	
	public void createRelationshipMovieDirector(GraphDatabaseService graph, Node movie, MovieTO movieTo){
		System.out.println("Create index for director...");
		Index<Node> index = graph.index().forNodes(Keys.INDEXDIRECTOR);
		Node node = index.get(Keys.DIRECTORKEY, movieTo.getDirector().toLowerCase()).getSingle();
		System.out.println("Node: " + node);
		Relationship relationship = node.createRelationshipTo(movie, RelTypes.DIRECTED);
	}
	
	public void createRelationshipMovieGender(GraphDatabaseService graph, Node movie, MovieTO movieTo) {
		System.out.println("Create index for gender");
		Index<Node> index = graph.index().forNodes(Keys.INDEXGENDER);
		Node node = index.get(Keys.GENDERKEY, movieTo.getGender().toLowerCase()).getSingle();
		if (node == null) {
			GenderDAO genderDAO = new GenderDAO();
			node = genderDAO.saveGenderGraph(movieTo.getGender(),index,graph);
		}
		System.out.println("Node " + node);
		if (node != null) {
			Relationship relationship = movie.createRelationshipTo(node, RelTypes.BELONGS);
		}
	}
	public static boolean createRelationshipUserMovie(GraphDatabaseService graph, Node user, String titleMovie) {
		Index<Node> index = graph.index().forNodes(Keys.INDEXMOVIE);
		Node node = index.get(Keys.MOVIEKEY, titleMovie.toLowerCase()).getSingle();
		System.out.println("Node user: " + user);
		System.out.println("Node movie: " + node);
		if (node != null) {
			Relationship relationship = user.createRelationshipTo(node, RelTypes.WATCHED);
			return true;
		}
		return false;
	}
}
